package com.findtech.threePomelos.activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVUser;
import com.baidu.autoupdatesdk.AppUpdateInfo;
import com.baidu.autoupdatesdk.AppUpdateInfoForInstall;
import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.CPCheckUpdateCallback;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.findtech.threePomelos.R;
import com.findtech.threePomelos.adapter.AboutAdapter;
import com.findtech.threePomelos.adapter.AdapterItemDecoration;
import com.findtech.threePomelos.base.MyActionBarActivity;
import com.findtech.threePomelos.base.MyApplication;
import com.findtech.threePomelos.login.LoginActivity;
import com.findtech.threePomelos.utils.RequestUtils;
import com.findtech.threePomelos.login.ThirdPartyController;
import com.findtech.threePomelos.utils.ToastUtil;
import com.findtech.threePomelos.view.dialog.CustomDialog;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.listener.SocializeListeners;

import java.util.ArrayList;

public class AboutActivity extends MyActionBarActivity implements View.OnClickListener, RequestUtils.MyItemClickListener {

    private RecyclerView mRecyclerView;
    private TextView mVersionNameTextView;
    private AboutAdapter mAdapter;
    private ImageView mLogoImage;
    private String strCheckVersion;
    private String strUserAgreement;
    private String strLogout;
    private ArrayList<String> listItem = new ArrayList<>();
    private ThirdPartyController mThirdPartyController;
    private String mVersionNameStr = null;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_about_info);
        MyApplication.getInstance().addActivity(this);
        setToolbar(getResources().getString(R.string.text_activity_title_app_about), true);
        strCheckVersion = getResources().getString(R.string.app_about_text_check_version);
        strUserAgreement = getResources().getString(R.string.app_about_text_user_agreement);
        strLogout = getResources().getString(R.string.app_about_text_log_out);
        mVersionNameTextView = (TextView) findViewById(R.id.text_app_version);
        mVersionNameStr = getmVersionNameStrNameFromApp();
        mVersionNameTextView.setText(mVersionNameStr);
        mLogoImage = (ImageView) findViewById(R.id.about_app_logo);
//        mAdapter = new MyAdapter();
        mAdapter = new AboutAdapter(this);
        mRecyclerView = (RecyclerView) findViewById(R.id.app_about_info_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new AdapterItemDecoration(this));
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        initProgressDialog();
    }

    @Override
    protected void onResume() {
        mThirdPartyController = new ThirdPartyController(this);
        listItem.add(strCheckVersion);
        listItem.add(strUserAgreement);
        listItem.add(strLogout);
        mAdapter.setListItem(listItem);
        super.onResume();
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case 0:
                progressDialog.setMessage("检测版本更新中，请稍后...");
                progressDialog.show();
                BDAutoUpdateSDK.cpUpdateCheck(this, new CPCheckUpdateCallback() {
                    @Override
                    public void onCheckUpdateCallback(AppUpdateInfo appUpdateInfo, AppUpdateInfoForInstall appUpdateInfoForInstall) {
                        if (appUpdateInfoForInstall != null && !TextUtils.isEmpty(appUpdateInfoForInstall.getInstallPath())) {
                            BDAutoUpdateSDK.uiUpdateAction(getApplicationContext(), new MyUICheckUpdateCallback());
                        } else if (appUpdateInfo != null) {
                            BDAutoUpdateSDK.uiUpdateAction(getApplicationContext(), new MyUICheckUpdateCallback());
                        } else {
                            ToastUtil.showToast(AboutActivity.this, "当前版本已经是最新版本了！");
                        }
                        progressDialog.dismiss();
                    }
                });
                break;
            case 1:
                startActivity(new Intent(this, GetUserProtocolActivity.class));
                break;
            case 2:
                showVerifyLogoutDialog();
                break;
        }
    }

    /**
     * 确认是否退出登录
     */
    private void showVerifyLogoutDialog() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("提示");
        builder.setNotifyInfo("确认退出登录？");

        builder.setShowButton(true);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                logOut();
                dialog.dismiss();
                RequestUtils.getSharepreferenceEditor(AboutActivity.this).clear().commit();
                startActivity(new Intent(AboutActivity.this, LoginActivity.class));
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public void onClick(View view) {
        if (view == mLogoImage) {
        }
    }

    public int getmVersionNameStrCodeFromApp() {
        int currentVersionCode = 0;
        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            currentVersionCode = info.versionCode; // android studio 版本号 in build.gradle file not in androidmanifest.xml
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return currentVersionCode;

    }

    public String getmVersionNameStrNameFromApp() {
        String mVersionNameStrName = null;
        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            mVersionNameStrName = info.versionName; //android studio 版本名 in build.gradle file not in androidmanifest.xml
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return mVersionNameStrName;

    }


    public void logOut() {
        AVUser.logOut();
        if (!mThirdPartyController.getUMSocialServiceLoginInstance().getEntity().mInitialized) {
            mThirdPartyController.getUMSocialServiceLoginInstance().initEntity(this,
                    new SocializeListeners.SocializeClientListener() {

                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onComplete(int status, SocializeEntity entity) {
                            if (status == 200) {
                                // 执行删除授权
                                mThirdPartyController.getUMSocialServiceLoginInstance().deleteOauth(
                                        getApplicationContext(), SHARE_MEDIA.WEIXIN,
                                        new SocializeListeners.SocializeClientListener() {
                                            @Override
                                            public void onStart() {
                                            }

                                            @Override
                                            public void onComplete(int status, SocializeEntity entity) {
                                                Log.d("ZZ", "deleteOauth status = " + status);
                                                if (status == 200) {
                                                    Log.d("ZZ", "删除成功1.");
                                                    Toast.makeText(AboutActivity.this, "退出成功", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    Log.d("ZZ", "删除失败1.");
                                                }
                                            }
                                        }
                                );
                            }
                        }
                    });
        } else {
            // 执权行删除授权
            mThirdPartyController.getUMSocialServiceLoginInstance().deleteOauth(this, SHARE_MEDIA.WEIXIN,
                    new SocializeListeners.SocializeClientListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onComplete(int status, SocializeEntity entity) {
                            Log.d("ZZ", "deleteOauth status = " + status);
                            if (status == 200) {
                                Log.d("ZZ", "删除成功.");
                                Toast.makeText(AboutActivity.this, "退出成功", Toast.LENGTH_SHORT).show();

                            } else {
                                Log.d("ZZ", "删除失败.");
                            }
                        }
                    }
            );
        }
    }

    private class MyUICheckUpdateCallback implements UICheckUpdateCallback {
        @Override
        public void onCheckComplete() {
        }
    }

    private void initProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setIndeterminate(true);
    }
}
